<template>
  <Panel title="重点车辆" v-bind="$attrs">
    <!-- tab切换部分  -->
    <div class="button-group">
      <a-radio-group v-model:value="state.vehicleType" button-style="solid" @change="handerSwitch">
        <a-radio-button
          :value="item.vehicleType"
          v-for="item in btns"
          :key="item.text"
          :class="state.vehicleType == item.vehicleType ? 'btn active' : 'btn'"
          >{{ item.text }}</a-radio-button
        >
      </a-radio-group>
      <svg-icon
        icon-class="search"
        class="icon-search"
        @click="searchShow = !searchShow"
        :style="{ color: searchShow ? '#fd8419' : '' }"
      ></svg-icon>
    </div>
    <!-- 切换关注车辆 -->
    <div class="switch-group">
      <!-- 超限预警高亮显示 -->
      <div class="arrow-box">
        <div class="arrow normal" :class="{ active: isStar == 'normal' }" @click="setStar('normal')">
          {{ state.vehicleType == 1 ? '疑似非法' : '超限预警' }}
        </div>
        <div class="arrow focus" :class="{ active: isStar == 'focus' }" @click="setStar('focus')">关注车辆</div>
      </div>

      <!-- 违法车辆车次统计 -->
      <div class="car-num-item">
        <div class="vehicle-count-box" v-if="state.vehicleType == 1">
          <span class="vehicle-count vehicle-total-count"
            >共计：<span>{{ computedVehicleStatistics.total || 0 }}</span
            >辆</span
          >
        </div>
        <div class="vehicle-count-box" v-else>
          <span class="vehicle-count"
            >违法车辆:<span>{{ computedVehicleStatistics.illegalVehicle || 0 }}</span
            >辆</span
          >
          <span class="vehicle-count"
            >违法车次:<span>{{ computedVehicleStatistics.illegalTrains || 0 }}</span
            >次</span
          >
        </div>
      </div>
    </div>

    <!-- 搜索部分 -->
    <Transition name="left">
      <div v-show="searchShow">
        <div class="search-group">
          <a-input v-model:value="state.plateNum" placeholder="车牌号" class="car" />
          <a-select ref="colorSelect" placeholder="车牌颜色" class="color" v-model:value="state.plateColor" allowClear>
            <a-select-option v-for="(color, index) in carColor" :key="index" :value="color.name">{{
              color.name
            }}</a-select-option>
          </a-select>
          <a-cascader
            ref="colorSelect"
            mode="multiple"
            :options="warnOptions"
            allowClear
            placeholder="预警标签"
            class="earlyLabel"
            multiple
            max-tag-count="responsive"
            v-model:value="state.earlyLabel"
            v-show="state.vehicleType != 1"
          >
          </a-cascader>
        </div>

        <!-- 查询重置 -->
        <div class="operates-group">
          <a-cascader
            v-model:value="state.value"
            class="cascader"
            allowClear
            max-tag-count="responsive"
            multiple
            :options="options"
            placeholder="触网位置"
          >
          </a-cascader>
          <div class="operates-btns">
            <a-button type="primary" class="query" @click="getData">查询</a-button>
            <a-button type="primary" class="reset" @click="reset">重置</a-button>
          </div>
        </div>
      </div>
    </Transition>

    <!-- 表格内容部分 -->
    <div class="table">
      <ScrollTable
        scroll="calc(100% - 0.32rem)"
        @tableClick="tableClick"
        @change="changePagination"
        v-model:pagination="paginationOptions"
        rowKey="id"
        :activeId="activeId"
        :columns="columns"
        :dataSource="state.dataSource"
        class="table-content"
        :loading="state.loading"
      >
        <!-- 车辆是否关注 -->
        <template v-slot:followStatus="{ text, record }">
          <svg-icon icon-class="focus-on" v-if="text === 0" @click="switchFocus(1, record)"> </svg-icon>
          <svg-icon icon-class="focus-not" v-else @click="switchFocus(0, record)"> </svg-icon>
        </template>

        <!-- 车牌号 -->
        <template v-slot:plateNum="{ text, record }">
          <div
            class="car-color"
            :style="{
              background: getCarColor(record)
            }"
          >
            {{ text }}
          </div>
        </template>

        <!-- 预警标签 -->
        <!-- <template v-slot:earlyLabel="{ text, record }">
          {{ warnList[text] || '--' }}
        </template> -->

        <!-- 触网位置 -->
        <!-- <template v-slot:netPosition="{ text, record }">
          <div>{{ locationList[text] || '--' }}</div>
        </template> -->

        <!-- 定位状态 -->
        <template v-slot:gpsStatus="{ text }">
          <svg-icon icon-class="gps-off-line" className="gps-status" v-if="text === 1"></svg-icon>
          <svg-icon icon-class="gps-on-line" className="gps-status" v-else></svg-icon>
        </template>
      </ScrollTable>
    </div>
  </Panel>
</template>
<script>
export default {
  name: 'CarList'
}
/**
 * @desc  重点车辆列表
 * @auther 邓清波
 * @date  2022/10/26
 * **/
</script>
<script setup>
import Panel from '../../components/panel'
import { getCurrentInstance, onMounted, reactive, ref, computed, defineEmits } from 'vue'
import ScrollTable from '../../components/scroll-table'
import monitorApi from '../../api/monitor'

// emit回调方法
const emit = defineEmits(['setDetail'])

const btns = [
  {
    text: '大件运输',
    vehicleType: 0
  },
  {
    text: '营运客车',
    vehicleType: 1
  },
  {
    text: '危化品车',
    vehicleType: 2
  },
  {
    text: '超限车辆',
    vehicleType: 3
  }
]
// 表格选中项
const activeId = ref()

const { proxy } = getCurrentInstance()
const state = reactive({
  vehicleType: 0,
  plateNum: null,
  plateColor: '黄',
  earlyLabel: [['超次运输'], ['未按路线行驶'], ['无'], ['超重']], // 预警标签
  value: [['shengjie'], ['shengnei']],
  dataSource: [],
  vehicleStatistics: [], // 车辆统计,
  loading: false
})

// 分页配置
const paginationOptions = ref({
  total: 0,
  pageSize: 10,
  current: 1
  // responsive: true,
  // showSizeChanger: true,
  // simple: true
})

// 当前查询维度的车辆统计
const computedVehicleStatistics = computed(() => {
  const findResult = state.vehicleStatistics.find(i => i.type === Number(state.vehicleType))
  return Array.isArray(findResult) ? findResult[0] : {}
})

const warnOptions = ref([
  { value: '无', label: '无' },
  { value: '超重', label: '超重' },
  { value: '超次运输', label: '超次运输' },
  { value: '未按路线行驶', label: '未按路线行驶' },
  { value: '未办理许可证', label: '未办理许可证' }
])
const options = [
  {
    value: 'shengjie',
    label: '省界',
    children: [
      {
        value: 'Hangzhou1',
        label: ' 苏鲁省界'
      },
      {
        value: 'Hangzhou2',
        label: ' 苏浙省界'
      },

      {
        value: 'Hangzhou',
        label: ' 苏沪省界'
      },
      {
        value: 'Hangzhou4',
        label: '苏皖省界'
      }
    ]
  },
  {
    value: 'shengnei',
    label: '省内',
    children: [
      {
        value: 'nanjing1',
        label: '南京市'
      },
      {
        value: 'nanjing2',
        label: '无锡市'
      },
      {
        value: '320300',
        label: '徐州市'
      },
      {
        value: 'nanjing4',
        label: '常州市'
      },
      {
        value: 'nanjing5',
        label: '苏州市'
      },
      {
        value: 'nanjing6',
        label: '南通市'
      },
      {
        value: 'nanjing7',
        label: '连云港市'
      },
      {
        value: 'nanjing8',
        label: '淮安市'
      },
      {
        value: 'nanjing9',
        label: '盐城市'
      },
      {
        value: 'nanjing10',
        label: '扬州市'
      },
      {
        value: 'nanjing11',
        label: '镇江市'
      },
      {
        value: 'nanjing12',
        label: '泰州市'
      },
      {
        value: 'nanjing13',
        label: '宿迁市'
      }
    ]
  }
]
const isStar = ref('normal') // 是否查询已关注状态
// 是否显示查询条件
const searchShow = ref(false)
// 表格表头
const columns = ref([])

// 超限预警表格couumn
const baseColumns = [
  {
    title: '',
    dataIndex: 'followStatus',
    key: 'followStatus',
    align: 'center',
    width: '8%'
  },
  {
    title: '车牌号',
    dataIndex: 'plateNum',
    key: 'plateNum',
    align: 'left',
    ellipsis: true,
    width: '20%'
  },
  {
    title: '预警标签',
    dataIndex: 'earlyLabel',
    key: 'earlyLabel',
    align: 'center',
    ellipsis: true
  },
  {
    title: '触网位置',
    dataIndex: 'netPosition',
    key: 'netPosition',
    align: 'center',
    customRender({ value }, text) {
      return value || '--'
    },
    ellipsis: true
  },
  {
    title: '预警时间',
    dataIndex: 'earlyTime',
    key: 'earlyTime',
    align: 'center',
    ellipsis: true,
    customRender({ value }, text) {
      return value ? proxy.$dayjs(value).format('HH:mm') : '--'
    }
  },
  {
    title: '定位状态',
    dataIndex: 'gpsStatus',
    key: 'gpsStatus',
    align: 'center',
    ellipsis: true
  }
]

// 关注车辆表头couumn
const focusColumns = [
  {
    title: '',
    dataIndex: 'followStatus',
    key: 'followStatus',
    align: 'center',
    width: '8%'
  },
  {
    title: '车牌号',
    dataIndex: 'plateNum',
    key: 'plateNum',
    align: 'left',
    ellipsis: true,
    width: '22%'
  },
  {
    title: '途经点',
    dataIndex: 'viaPoint',
    key: 'viaPoint',
    align: 'center',
    customRender({ value }, text) {
      return value || '--'
    },
    ellipsis: true
  },
  {
    title: '监测时间',
    dataIndex: 'earlyTime',
    key: 'earlyTime',
    align: 'center',
    ellipsis: true,
    customRender({ value }, text) {
      return value ? proxy.$dayjs(value).format('HH:mm') : '--'
    }
  }
]

// 营运客车-疑似非法表头
const operatGuest = [
  {
    title: '',
    dataIndex: 'followStatus',
    key: 'followStatus',
    align: 'center',
    width: '8%'
  },
  {
    title: '车牌号',
    dataIndex: 'plateNum',
    key: 'plateNum',
    align: 'left',
    ellipsis: true,
    width: '22%'
  },
  {
    title: '频次',
    dataIndex: 'frequency',
    key: 'frequency',
    align: 'center',
    customRender({ value }, text) {
      return value || '--'
    },
    sorter: (a, b) => a.frequency - b.frequency,
    ellipsis: true
  },
  {
    title: '预警时间',
    dataIndex: 'earlyTime',
    key: 'earlyTime',
    align: 'center',
    ellipsis: true,
    customRender({ value }, text) {
      return value ? proxy.$dayjs(value).format('HH:mm') : '--'
    }
  },
  {
    title: '触网位置',
    dataIndex: 'netPosition',
    key: 'netPosition',
    align: 'center',
    customRender({ value }, text) {
      return value || '--'
    },
    ellipsis: true
  }
]

// 车牌颜色
const carColor = ref([
  { name: '黄', color: '#FFBE00' }
  // { name: '蓝', color: '#0B89ED' },
  // { name: '绿', color: '#4c8d23' }
])
// 预警标签
const warnList = ['无', '超重', '超次运输', '未按路线行', '百吨王']
// 触网位置
// const locationList = reactive({ 0: '省界' }, { 1: '省内' })

onMounted(() => {
  columns.value = baseColumns
  init()
})

/**
 * 初始化
 * **/
function init() {
  getData()
}

const getCarColor = record => {
  const arr = carColor.value.filter(item => item.name == record.plateColor)
  return arr ? arr[0].color : null
}

/**
 * 获取数据
 * **/
function getData() {
  state.loading = true
  const params = {
    plateNum: state.plateNum, // 车牌号
    plateColor: state.plateColor, // 车牌颜色
    earlyLabel: state.earlyLabel ? state.earlyLabel.join(',') : null, // 预警标签
    // 触网位置
    province: 32, // 省
    city: '', // 市
    vehicleType: state.vehicleType, // 车辆类型(0：大件运输车；1：运营客车；2：危化品车；3：超限车辆)
    followStatus: isStar.value == 'focus' ? 0 : null, // 列表关注状态(0:已关注;1:未关注)
    page: paginationOptions.value.current,
    limit: paginationOptions.value.pageSize
  }
  monitorApi
    .getScreenVehicleList(params)
    .then(res => {
      console.log('获取车辆列表', res)
      state.dataSource = sortListByFollowStatus(res.data.list)
      // 默认展示第一项
      tableClick(state.dataSource[0])
      paginationOptions.value.total = res.data.total || 0
      paginationOptions.value.current = res.data.pageNum || 1
    })
    .finally(() => (state.loading = false))

  // 获取车辆统计
  monitorApi.getVehicleStatistic({}).then(res => {
    console.log('获取车辆统计', res)
    state.vehicleStatistics = res.data || []
  })
}

/**
 * @desc 根据关注状态排序
 * @param {list} Array
 * @reutrn  Array
 * */
function sortListByFollowStatus(list) {
  if (!Array.isArray(list)) return []
  return list.sort((a, b) => a.followStatus - b.followStatus)
}

/**
 * tab切换查询维度
 * **/
function handerSwitch(e) {
  // 表头内容
  if (isStar.value == 'focus') columns.value = focusColumns
  else if (e.target.value == 1) columns.value = operatGuest
  else columns.value = baseColumns

  if ([0].includes(e.target.value)) {
    carColor.value = [{ name: '黄', color: '#FFBE00' }]
    warnOptions.value = [
      { value: '无', label: '无' },
      { value: '超重', label: '超重' },
      { value: '超次运输', label: '超次运输' },
      { value: '未按路线行驶', label: '未按路线行驶' },
      { value: '未办理许可证', label: '未办理许可证' }
    ]
  } else if ([2].includes(e.target.value)) {
    carColor.value = [
      { name: '黄', color: '#FFBE00' },
      { name: '蓝', color: '#0B89ED' }
    ]
    warnOptions.value = [
      { value: '无', label: '无' },
      { value: '超重', label: '超重' },
      { value: '未按路线行驶', label: '未按路线行驶' }
    ]
  } else if ([3].includes(e.target.value)) {
    carColor.value = [
      { name: '黄', color: '#FFBE00' },
      { name: '蓝', color: '#0B89ED' }
    ]
    warnOptions.value = [
      { value: '超重', label: '超重' },
      { value: '百吨王', label: '百吨王' },
      { value: '未按路线行驶', label: '未按路线行驶' }
    ]
  } else {
    carColor.value = [
      { name: '黄', color: '#FFBE00' },
      { name: '蓝', color: '#0B89ED' },
      { name: '绿', color: '#4c8d23' }
    ]
    warnOptions.value = []
  }

  // 危化品车，车牌颜色，默认选中黄色
  if ([0, 2, 3].includes(e.target.value)) state.plateColor = '黄'
  else state.plateColor = null

  reset()
}

function reset() {
  state.plateNum = null

  // 车牌颜色，默认选中黄色
  state.plateColor = '黄'
  state.value = [['shengjie'], ['shengnei']]

  if ([0].includes(state.vehicleType)) {
    state.earlyLabel = [['超次运输'], ['未按路线行驶'], ['无'], ['超重'], ['未办理许可证']]
  } else if ([2].includes(state.vehicleType)) {
    state.earlyLabel = [['未按路线行驶'], ['无'], ['超重']]
  } else if ([3].includes(state.vehicleType)) {
    state.earlyLabel = [['超重'], ['百吨王'], ['未按路线行驶']]
  } else state.earlyLabel = []

  getData()
}

/**
 * @desc 表格分页
 * **/
function changePagination(options) {
  console.log(options)
  paginationOptions.value = options
  getData()
}

/**
 * 切换关注维度
 * **/
async function setStar(data) {
  isStar.value = data
  if (data == 'focus') columns.value = focusColumns
  else columns.value = baseColumns
  await getData()
  proxy.$bus.emit('vehicleClick', data)
}

/**
 * 表格行关注/取消关注
 * @param v value
 * @params redord 表格行
 * **/
function switchFocus(v, record) {
  monitorApi
    .switchFollowStatus({
      id: record.id,
      status: v
    })
    .then(res => {
      record['followStatus'] = v
      proxy.$message.success('操作成功')
      getData()
      // state.dataSource = sortListByFollowStatus(state.dataSource)
    })
    .catch(e => proxy.$message.error('操作失败'))
}

// 列表项点击
const tableClick = item => {
  if (item) activeId.value = item.id
  proxy.$bus.emit('vehicleClick', item)
}
</script>
<style scoped lang="less">
@import url(~@/assets/styles/transition.less);

/deep/ .mz-panel-content-main {
  justify-content: flex-start;
  padding-bottom: 0;
}

.button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 5px;

  .btn {
    text-align: center;
    padding: 0;
    width: 85px;
    height: 100%;
    line-height: 38px;
    margin-right: 10px;
    background: #ffffff;
    color: #000;
    border-radius: 2px;
  }

  .active {
    background: linear-gradient(270deg, #2564f2 0%, #298eff 100%);
    color: #fff;
  }

  .icon-search {
    width: 25px;
    height: 25px;
    cursor: pointer;
    color: rgb(65, 147, 255);
  }
}

.switch-group {
  height: 32px;
  background-color: #bddefb;
  display: flex;
  align-items: center;
  margin-top: 8px;

  .car-num-item {
    flex: 1;
    color: #333333;
    overflow: hidden;

    .vehicle-count-box {
      flex: 1;
      display: flex;
      font-size: 13px;
      letter-spacing: -0.5px;
      display: flex;
      text-align: right;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .vehicle-count {
      flex: 1;
      margin-right: 2px;
    }

    .vehicle-total-count {
      margin-right: 10px;
    }
  }

  .arrow-box {
    display: flex;
    height: 100%;
    width: 51.5%;

    .arrow {
      width: 60%;
      height: 100%;
      background: url('../../assets/images/important-car/carList-white-arrow.png') left no-repeat;
      background-size: 100% 100%;
      cursor: pointer;

      &.normal {
        z-index: 9;
        padding: 5px 0 0 21px;
      }

      &.focus {
        margin-left: -25px;
        padding: 5px 0 0 30px;
      }

      &.active {
        background: url('../../assets/images/important-car/carList-blue-arrow.png') left no-repeat;
        border: none;
        background-size: 100% 100%;
        color: #fff;
      }
    }
  }
}

.search-group {
  display: flex;
  margin: 8px 0;
  justify-content: space-between;

  /deep/ .ant-select-selector {
    height: 100%;
  }

  .car {
    // width: 29%;
    flex: 1;
    margin-right: 15px;
  }

  .color {
    width: 29%;
    margin-right: 15px;
  }

  .earlyLabel {
    width: 34%;
  }
}

.operates-group {
  display: flex;

  .operates-btns {
    margin-left: 10px;
    width: 35%;
    display: flex;
    height: 30px;
    align-items: center;
    margin-top: 2px;

    .reset {
      flex: 1;
      margin-left: 5px;
      background-color: #fff;
      color: #333;
      line-height: 16px;
      height: 100%;
      padding: 0;
    }

    .query {
      flex: 1;
      margin-left: 5px;
      line-height: 16px;
      height: 100%;
      padding: 0;
    }
  }

  .cascader {
    flex: 1;
  }
}

.table {
  flex: 1;
  overflow: hidden;
  padding: 8px 0;

  .gps-status {
    font-size: 12px;
  }

  /deep/ .ant-table {
    margin-bottom: 15px;
  }

  /deep/.table-content {
    height: calc(100% - 50px);

    .car-color {
      text-align: center;
    }
  }
}

/deep/td.ant-table-column-sort {
  background: transparent;
}
/deep/ .ant-table-thead {
  .ant-table-cell {
    color: #333333 !important;
  }
}

/deep/.ant-pagination.ant-table-pagination {
  margin-top: 0 !important;
}
</style>
